T operator[] (size_t n) const;
T& operator[] (size_t n);
valarray<T> operator[] (slice slc) const;
slice_array<T> operator[] (slice slc);
valarray<T> operator[] (const gslice& gslc) const;
gslice_array<T> operator[] (const gslice& gslc);
valarray<T> operator[] (const valarray<bool>& msk) const;
mask_array<T> operator[] (const valarray<bool>& msk);
valarray<T> operator[] (const valarray<size_t>& ind) const;
indirect_array<T> operator[] (const valarray<size_t>& ind);
Access element or subscript
The first two versions access the n-th element in the valarray object: in a constant valarray, a copy of the element is returned; In a non-constant valarray, a reference.
For the remaining versions, the function produces a subarray from the subscript operation specifier. The constant versions return a new valarray object, while the non-constant versions return a subarray object which has reference semantics to the original array, ready to be used as an l-value.
Parameters
- n
- Position of an element in the valarray.
Notice that the first element has the position 0, not 1.
size_t is an unsigned integral type.
- slc
- A slice object specifying which elements conform the array or subarray returned.
- gslc
- A gslice object specifying which elements conform the array or subarray returned.
- msk
- A valarray with its member identifying whether each element of *this will be part of the returned valarray: If an element in *this has its corresponding element in msk set to true it is part of the returned valarray, otherwise it is not, shortening the resulting valarray.
- ind
- A valarray with its member indentifying which elements of *this will be part of the returned valarray: Each element in ind is the index of an element in *this that will be part of the returned valarray.
Return value
An element or a subarray of *this.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
// valarray::operator[] example
#include <iostream>
#include <valarray>
using namespace std;
int main ()
{
valarray<int> myarray (10); // 0 0 0 0 0 0 0 0 0 0
// slice:
myarray[slice(2,3,3)]=10; // 0 0 10 0 0 10 0 0 10 0
// gslice:
size_t lengths[]={2,2};
size_t strides[]={6,2};
myarray[gslice(1, valarray<size_t>(lengths,2), valarray<size_t>(strides,2))]=20;
// 0 20 10 20 0 10 0 20 10 20
// mask:
valarray<bool> mymask (10);
for (int i=0; i<10; ++i) mymask[i]= ((i%2)==0);
myarray[mymask] += valarray<int>(3,5); // 3 20 13 20 3 10 3 20 13 20
//indirect:
size_t sel[]= {2,5,7};
valarray<size_t> myselection (sel,3); // 3 20 99 20 3 99 3 99 13 20
myarray[myselection]=99;
cout << "myarray: ";
for (size_t i=0; i<myarray.size(); ++i)
cout << myarray[i] << ' ';
cout << endl;
return 0;
}
|
Output:
3 20 99 20 3 99 3 99 13 20
|
See also
slice | Valarray slice selector (class) |
gslice | Valarray generalized slice selector (class) |
|